<script lang="ts" setup>
import { Message } from '@arco-design/web-vue'
import { StudentApi } from '@/apis/education'
import type { TableInstanceColumns } from '@/components/ProTable/type'
import { useTable } from '@/hooks/modules/useTable'
import { useDictLabel, useDictOptions } from '@/hooks'
import { calculateStudentGradeLimit } from '@/utils/edu'

const props = defineProps<{ id: string | number }>()

const basedict = reactive({
  subjects: useDictOptions('Subject'),
  levels: [],
})

const {
  tableData,
  loading,
  pagination,
  search,
  handleDelete,
} = useTable(pagination => StudentApi.getStudentEnrollPermission({ ...pagination }, props.id))

watch(tableData, (_) => {
  tableData.value.forEach((item) => {
    item.admissionYear = item.admissionYear ? `${item.admissionYear}-01-01` : ''
  })
})

const columns: TableInstanceColumns[] = [
  {
    title: '序号',
    width: 66,
    align: 'center',
    fixed: 'left',
    render: ({ rowIndex }) => h('span', {}, rowIndex + 1 + (pagination.current - 1) * pagination.pageSize),
  },
  { title: '科目', slotName: 'subject', dataIndex: 'subject', width: 140 },
  { title: '年份', dataIndex: 'admissionYear', slotName: 'date', width: 140 },
  { title: '班级等级', dataIndex: 'classLevel', width: 140, slotName: 'classType' },
  { title: '注释', dataIndex: 'remark', slotName: 'remark', width: 340, ellipsis: true, tooltip: true },
  {
    title: '操作',
    slotName: 'action',
    width: 140,
    align: 'center',
    fixed: 'right',
  },
]

const baseData = () => {
  StudentApi.getClassType().then((res) => {
    basedict.levels = res || []
  })
}

// 新增
const onAdd = () => {
  if (tableData.value.length === 0 || !tableData.value[tableData.value.length - 1].isEdit) {
    tableData.value.push({
      id: undefined,
      isEdit: true,
      // sequence: tableData.value.length === 0 ? 1 : tableData.value[tableData.value.length - 1].sequence + 1,
      subject: undefined,
      admissionYear: undefined,
      // classTypeName: '',
      classLevel: undefined,
      remark: undefined,
      studentId: props.id,
    })
  } else {
    Message.warning('请先保存上一条数据')
  }
}

const updateLoading = ref(false)

const getLevelById = (id: string) => {
  if (!id || !basedict.levels.length) {
    return
  }
  return (basedict.levels.filter((item: any) => item.id === id)[0] as any).level
}

const operate = async (record) => {
  if (!record.isEdit) {
    record.isEdit = true
  } else {
    try {
      updateLoading.value = true
      console.log('xyear: ', record.admissionYear)
      const data = {
        ...record,
        admissionYear: record.admissionYear ? record.admissionYear.split('-')[0] : '',
        // classLevel: record.classLevel,
        studentId: props.id,
      }
      if (record.id) { // 修改
        await StudentApi.updateClassPermission(data, record.id)
      } else { // 新增
        await StudentApi.addClassPermission(data)
      }

      record.isEdit = false
      Message.success('修改成功')
    } finally {
      updateLoading.value = false
    }
  }
}

const delLoading = ref(false)
const getLevelName = (level: number) => {
  const obj: any = basedict.levels.filter((item: any) => item.id === level)
  if (obj.length) {
    return obj[0].name
  }
  return '-'
}

const onClassTypeSelect = (item, record) => {
  if (!item?.level) {
    nextTick(() => {
      record.classLevel = undefined
    })
  } else {
    record.classLevel = item.level
  }
}

// 删除
const onDelete = (item) => {
  if (!item.id) {
    Message.error('请先保存！')
    return false
  }
  return handleDelete(() => StudentApi.deleteClassPermission(item.id), {
    content: `是否确定删除该条数据？`,
    showModal: true,
  })
}

// 取消
const onCancel = (item, rowIndex) => {
  search()
}

watch(() => props.id, () => search())

onMounted(() => {
  baseData()
})
</script>

<template>
  <ProTable
    :data="tableData" :columns="columns" :loading="loading" :pagination="pagination" @refresh="search"
  >
    <template #toolbar-left>
      <a-button v-permission="['edu:student:manage']" type="primary" size="small" @click="onAdd">
        <icon-plus />
        新增权限
      </a-button>
    </template>
    <template #subject="{ record }">
      <DictSelect v-if="record.isEdit" v-model="record.subject" placeholder="请选择科目" code="Subject" />
      <!-- <a-select v-if="record.isEdit" v-model="record.subject" placeholder="请选择科目" :options="basedict.subjects" /> -->
      <span v-else>{{ useDictLabel('Subject', record.subject) }}</span>
    </template>
    <template #date="{ record }">
      <a-year-picker v-if="record.isEdit" v-model="record.admissionYear" placeholder="请选择年份" />
      <span v-else>{{ record.admissionYear ? record.admissionYear.split('-')[0] : '' || '-' }}</span>
    </template>
    <template #classType="{ record }">
      <ClassTypeSelect v-if="record.isEdit" @select="onClassTypeSelect($event, record)" />
      <!-- <a-select v-if="record.isEdit" v-model="record.classLevel" placeholder="请选择班级类型" :options="basedict.levels" :field-names="{ value: 'id', label: 'name' }" /> -->
      <!-- <span v-else>{{ getLevelName(record.classTypeId) }}</span> -->
      <span v-else>{{ record.classLevel }}</span>
    </template>
    <template #remark="{ record }">
      <div style="font-size: 13px">
        <span>允许报名班级等级</span>
        <span class="font-600">&lt;={{ record.classLevel }}</span>
        <span>的</span>
        <span class="font-600">{{ calculateStudentGradeLimit(record.admissionYear) }}{{ useDictLabel('Subject', record.subject) }}</span>
        <span>班级</span>
      </div>
    </template>
    <template #action="{ record, rowIndex }">
      <a-space v-if="record.isEdit" v-permission="['edu:student:manage']">
        <a-link :loading="updateLoading" @click="operate(record)">
          保存
        </a-link>
        <a-link :loading="delLoading" @click="onCancel(record, rowIndex)">
          取消
        </a-link>
      </a-space>
      <a-space v-else v-permission="['edu:student:manage']">
        <a-link :loading="updateLoading" @click="operate(record)">
          编辑
        </a-link>
        <a-link :loading="delLoading" @click="onDelete(record)">
          删除
        </a-link>
      </a-space>
    </template>
  </ProTable>
</template>

<style lang="less" scoped>
.search-key {
  display: flex;
  align-items: center;

  .label {
    margin-left: 20px;
    margin-right: 10px;
  }
}

.status {
  font-size: 14px;
  padding-left: 10px;
  position: relative;

  &::before {
    position: absolute;
    content: '';
    width: 6px;
    height: 6px;
    background: #165dff;
    border-radius: 50%;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }
}

.status1 {
  color: #165dff;

  &::before {
    background: #165dff;
  }
}

.status2 {
  color: #1d2129;

  &::before {
    background: #c9cdd4;
  }
}

.status3 {
  color: #f53f3f;

  &::before {
    background: #f53f3f;
  }
}

.status4 {
  color: #ff7d00;

  &::before {
    background: #ff7d00;
  }
}
</style>
